package com.agileai.portal.message.service;

import java.util.List;

import javax.xml.soap.SOAPException;

import org.apache.cxf.binding.soap.SoapHeader;
import org.apache.cxf.binding.soap.SoapMessage;
import org.apache.cxf.headers.Header;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import org.apache.log4j.Logger;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;


public class AuthIntercetper extends AbstractPhaseInterceptor<SoapMessage>{
	private static final Logger logger = Logger.getLogger(AuthIntercetper.class);
	public static final String xml_namespaceUR_att = "http://service.portal.agileai.com/authentication";
	public static final String xml_authentication_el = "authentication";
	public static final String xml_userID_el = "userId";
	public static final String xml_password_el = "password";
	
	private String userId = null;
	private String password = null;
	

	public AuthIntercetper() {
		super(Phase.PRE_INVOKE);
	}

	
	public String getUserId() {
		return userId;
	}

	public void setUserId(String userId) {
		this.userId = userId;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}
	
	public void handleMessage(SoapMessage message) {
		List<Header> headers = message.getHeaders();

		if (null == headers || headers.size() < 1) {
			throw new Fault(new SOAPException("soap header is not valid !"));
		}
		for (Header header : headers) {
			SoapHeader soapHeader = (SoapHeader) header;
			Element element = (Element) soapHeader.getObject();
//			XMLUtils.printDOM(element);
			NodeList userIdNodes = element.getElementsByTagName(xml_userID_el);
			NodeList pwdNodes = element.getElementsByTagName(xml_password_el);
			if (null != userIdNodes
					&& userIdNodes.item(0).getTextContent().equals(userId) ) {
				if (null != pwdNodes
						&& pwdNodes.item(0).getTextContent().equals(password)) {
					logger.info(userIdNodes.item(0).getTextContent() + " auth successfully !");
				} else {
					SOAPException soapExc = new SOAPException("password is not valid !");
					throw new Fault(soapExc);
				}
			} else {
				SOAPException soapExc = new SOAPException("userId is not valid !");
				throw new Fault(soapExc);
			}
		}
	}
}
